package com.ctsi.commons.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.*;
import java.util.Currency;
import java.util.Locale;

public class UtilFormatOut {

	private static final Logger log = LoggerFactory.getLogger(UtilFormatOut.class);

	public static String safeToString(Object obj) {
		if (obj != null) {
			return obj.toString();
		} else {
			return "";
		}
	}

	// ------------------- 价格格式 -------------------
	final static DecimalFormat priceDecimalFormat = new DecimalFormat("#,##0.00");

	/**
	 * 格式化价格
	 * 
	 * @param price
	 * @return
	 */
	public static String formatPrice(Double price) {
		if (price == null)
			return "";
		return formatPrice(price.doubleValue());
	}

	/**
	 * 格式化价格
	 * 
	 * @param price
	 * @return
	 */
	public static String formatPrice(double price) {
		return priceDecimalFormat.format(price);
	}

	public static Double formatPriceNumber(double price) {
		try {
			return Double.valueOf(priceDecimalFormat.parse(formatPrice(price)).doubleValue());
		} catch (ParseException e) {
			log.warn("formatPriceNumber error :{}",e.getMessage());
			return Double.valueOf(price);
		}
	}

	/**
	 * 格式化货币
	 * @param price
	 * @return
	 */
	public static String formatCurrency(double price ) {
		return formatCurrency(price,null,Locale.getDefault());
	}
	/**
	 * 格式化货币
	 * 
	 * @param price
	 *            金额
	 * @param isoCode
	 *            iso编码
	 * @param locale
	 *            地区
	 * @return 格式化字符串
	 */
	public static String formatCurrency(double price, String isoCode, Locale locale) {
		assert (locale != null);
		NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
		if (isoCode != null && isoCode.length() > 1) {
			nf.setCurrency(Currency.getInstance(isoCode));
		} else {
			log.info("No isoCode specified to format currency value:{}" , price);
		}
		return nf.format(price);
	}

	/**
	 * 格式化货币
	 * 
	 * @param price
	 *            金额
	 * @param isoCode
	 *            货币iso编码
	 * @param locale
	 *            地区 
	 * @return A String with the formatted price
	 */
	public static String formatCurrency(Double price, String isoCode, Locale locale) {
		return formatCurrency(price.doubleValue(), isoCode, locale);
	}

	// ------------------- 百分比格式 -------------------
	static DecimalFormat percentageDecimalFormat = new DecimalFormat("##0.##%");

	/**
	 * 格式化百分比
	 * 
	 * @param percentage
	 *            需要格式化的百分比
	 * @return 格式化结果 
	 */
	public static String formatPercentage(Double percentage) {
		if (percentage == null)
			return "";
		return formatPercentage(percentage.doubleValue());
	}

	/**
	 * 格式化百分比
	 * 
	 * @param percentage
	 *            需要格式化的百分比
	 * @return  格式化结果 
	 */
	public static String formatPercentage(double percentage) {
		return percentageDecimalFormat.format(percentage);
	}

	// ------------------- 数量格式-------------------
	final static DecimalFormat quantityDecimalFormat = new DecimalFormat("#,##0.###");

	/**
	 * 格式化long数字
	 * 
	 * @param quantity
	 *            需要格式化数字
	 * @return 格式化完毕后数字
	 */
	public static String formatQuantity(Long quantity) {
		if (quantity == null)
			return "";
		else
			return formatQuantity(quantity.doubleValue());
	}

	/**
	 * 格式化数量
	 * 
	 * @param quantity
	 *            待格式化数量
	 * @return A String 格式化字符串
	 */
	public static String formatQuantity(long quantity) {
		return formatQuantity((double) quantity);
	}

	/**
	 * 格式化integer 数字
	 * 
	 * @param quantity
	 *            待格式化数量
	 * @return A String 格式化字符串
	 */
	public static String formatQuantity(Integer quantity) {
		if (quantity == null)
			return "";
		else
			return formatQuantity(quantity.doubleValue());
	}

	/**
	 * 格式化integer 数字
	 * 
	 * @param quantity
	 *             待格式化数字
	 * @return A String 格式化字符串
	 */
	public static String formatQuantity(int quantity) {
		return formatQuantity((double) quantity);
	}

	/**
	 * 格式化Float 数字
	 * 
	 * @param quantity
	 *            待格式化数字
	 * @return A String 格式化字符串
	 */
	public static String formatQuantity(Float quantity) {
		if (quantity == null)
			return "";
		else
			return formatQuantity(quantity.doubleValue());
	}

	/**
	 * 格式化float数量
	 * 
	 * @param quantity
	 *            需要格式化的数量
	 * @return A String 格式化字符串
	 */
	public static String formatQuantity(float quantity) {
		return formatQuantity((double) quantity);
	}

	/**
	 * 格式化Double数量
	 * 
	 * @param quantity
	 *            需要格式化的数量
	 * @return A String 格式化字符串
	 */
	public static String formatQuantity(Double quantity) {
		if (quantity == null)
			return "";
		else
			return formatQuantity(quantity.doubleValue());
	}

	/**
	 * 格式化double
	 * 
	 * @param quantity
	 *            需要格式化的数字
	 * @return 格式化字符串
	 */
	public static String formatQuantity(double quantity) {
		return quantityDecimalFormat.format(quantity);
	}

	public static String formatPaddedNumber(long number, int numericPadding) {
		StringBuilder outStrBfr = new StringBuilder(Long.toString(number));
		while (numericPadding > outStrBfr.length()) {
			outStrBfr.insert(0, '0');
		}
		return outStrBfr.toString();
	}

	public static String formatPaddingRemove(String original) {
		if (original == null)
			return null;
		StringBuilder orgBuf = new StringBuilder(original);
		while (orgBuf.length() > 0 && orgBuf.charAt(0) == '0') {
			orgBuf.deleteCharAt(0);
		}
		return orgBuf.toString();
	}

	// ------------------- date handlers -------------------
	/**
	 * 格式化Timestamp
	 */
	public static String formatDate(java.sql.Timestamp timestamp) {
		if (timestamp == null)
			return "";
		DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);

		return df.format(timestamp);
	}

	public static String formatDate(long timestamp  ){
		return formatDate(timestamp,null);
	}
	public static String formatDate(long timestamp , String datePattern) {
		DateFormat df;
		if (UtilValidate.isEmpty(datePattern))
		  df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
		else
			df = new SimpleDateFormat(datePattern);
		java.util.Date date = new java.util.Date(timestamp);
		return df.format(date);
	}

	// ------------------- null string handlers -------------------


	/**
	 * String null检查
	 * 
	 * @param string1
	 * @return
	 */
	public static String checkNull(String string1) {
		if (string1 != null)
			return string1;
		else
			return "";
	}


	// ------------------- web encode handlers -------------------
	/**
	 * url 编码 替换% 空格等
	 * 
	 * @param query
	 *            需要编码的 String
	 * @return The encoded String
	 */
	public static String encodeQuery(String query) {
		String retString;

		retString = StringUtil.replaceString(query, "%", "%25");
		retString = StringUtil.replaceString(retString, " ", "%20");
		return retString;
	}

	/**
	 * url参数编码
	 * 
	 * @param query
	 *            The plain query value String
	 * @return The encoded String
	 */
	public static String encodeQueryValue(String query) {
		String retString;

		retString = StringUtil.replaceString(query, "%", "%25");
		retString = StringUtil.replaceString(retString, " ", "%20");
		retString = StringUtil.replaceString(retString, "&", "%26");
		retString = StringUtil.replaceString(retString, "?", "%3F");
		retString = StringUtil.replaceString(retString, "=", "%3D");
		return retString;
	}

 

	/**
	 * url编码解码
	 *  
	 * 
	 * @param query
	 *            The encoded query value String
	 * @return The plain, decoded String
	 */
	public static String decodeQueryValue(String query) {
		String retString;

		retString = StringUtil.replaceString(query, "%25", "%");
		retString = StringUtil.replaceString(retString, "%20", " ");
		retString = StringUtil.replaceString(retString, "%26", "&");
		retString = StringUtil.replaceString(retString, "%3F", "?");
		retString = StringUtil.replaceString(retString, "%3D", "=");
		return retString;
	}

	
	/**
	 * xml特殊符号编码 '<', '>', '"', ''', '&'
	 * 
	 * @param inString
	 *            The plain value String
	 * @return The encoded String
	 */
	public static String encodeXmlValue(String inString) {
		String retString = inString;

		retString = StringUtil.replaceString(retString, "&", "&amp;");
		retString = StringUtil.replaceString(retString, "<", "&lt;");
		retString = StringUtil.replaceString(retString, ">", "&gt;");
		retString = StringUtil.replaceString(retString, "\"", "&quot;");
		retString = StringUtil.replaceString(retString, "'", "&apos;");
		return retString;
	}

	public static String decodeXmlValue(String inString) {
		String retString = inString;

		retString = StringUtil.replaceString(retString, "&amp;", "&");
		retString = StringUtil.replaceString(retString, "&lt;", "<");
		retString = StringUtil.replaceString(retString, "&gt;", ">");
		retString = StringUtil.replaceString(retString, "&quot;", "\"");
		retString = StringUtil.replaceString(retString, "&apos;", "'");
		return retString;
	}

	public static String padString(String str, int setLen, boolean padEnd, char padChar) {
		if (str == null) {
			return null;
		}
		if (setLen == 0) {
			return str;
		}
		int stringLen = str.length();
		int diff = setLen - stringLen;
		if (diff < 0) {
			return str.substring(0, setLen);
		} else {
			String newString = new String();
			if (padEnd) {
				newString = newString + str;
			}
			for (int i = 0; i < diff; i++) {
				newString = newString + padChar;
			}
			if (!padEnd) {
				newString = newString + str;
			}
			return newString;
		}
	}
}
